﻿using OD.ProjectCustomizationTool.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OD.ProjectCustomizationTool
{
    internal abstract class SingleLineFileUpdaterBase : FileUpdaterBase
    {
        #region Properties

        /// <summary>
        /// Retrieve the string to search.
        /// </summary>
        protected abstract String SearchPattern { get; }

        /// <summary>
        /// Retrieve the string to replace if the search pattern string exists in the file.
        /// </summary>
        protected virtual String ReplaceLineWith { get { return this.SearchPattern; } }

        /// <summary>
        /// Retrieve the comment string to add before the line to add or update.
        /// </summary>
        protected virtual String CommentToAddBeforeReplacePattern { get { return String.Empty; } }

        /// <summary>
        /// Indicates if the update of the line is allowed or if there is only the adding functionality.
        /// </summary>
        protected virtual Boolean IsAllowedUpdatingLine { get { return true; } }

        #endregion

        protected override void InternalUpdate()
        {
            var content = File.ReadAllLines(this.FileFullPath).ToList();
            var lineIndex = content.FindIndex(x => !String.IsNullOrEmpty(x) && x.Contains(this.SearchPattern));

            if (lineIndex < 0)
            {
                this.Monitor.Logger.WriteLine("Adding '" + this.ReplaceLineWith + "' at the end of '" + this.FileRelativePath + "'.");
                if (!String.IsNullOrEmpty(this.CommentToAddBeforeReplacePattern))
                {
                    content.Add(String.Empty);
                    content.Add("// " + this.CommentToAddBeforeReplacePattern);
                }
                content.Add(this.ReplaceLineWith);
            }
            else if (this.IsAllowedUpdatingLine)
            {
                this.Monitor.Logger.WriteLine("Updating '" + this.ReplaceLineWith + "' in '" + this.FileRelativePath + "'.");
                content[lineIndex] = this.ReplaceLineWith;
            }
            else
            {
                this.Monitor.Logger.WriteLine("Keeping original line '" + content[lineIndex] + "' in '" + this.FileRelativePath + "'.");
            }

            File.WriteAllLines(this.FileFullPath, content);
        }
    }
}
